const mongoose = require("../conf/db");
const bcryptjs = require("bcryptjs");

const userSchema = new mongoose.Schema(
  {
    username: {
      type: String,
      required: true
    },

    password: {
      type: String,
      required: true
    },

    posts: {
      type: [
        {
          type: mongoose.SchemaTypes.ObjectId,
          ref: "post"
        }
      ]
    }
  },
  { timestamps: true }
);

userSchema.pre("save", async function(next) {
  const user = this;
  user.password = await bcryptjs.hash(user.password, 10);
  next();
});

/**
 * 密码校验
 * @param {String} password 需要校验的密码
 */
userSchema.methods.comparePassword = async function(password) {
  const user = this;
  return await bcryptjs.compare(password, user.password);
};

module.exports = mongoose.model("user", userSchema);
